<?php


/**
  +------------------------------------------------------------------------------
 * 淘宝采集管理
  +------------------------------------------------------------------------------
 */
class TmallCollectAction extends CommonAction
{
	public function index()
	{
            $_SESSION['taobao_collect_shop'] = 0;
		$model = D ('TaobaoCollect');
		$sql = 'SELECT COUNT(num_iid) AS tcount
			FROM '.C("DB_PREFIX").'taobao_collect ';

		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT * FROM '.C("DB_PREFIX").'taobao_collect ';
		$this->_sqlList($model,$sql,$count,$parameter,'num_iid');
		$this->display();
		return;
	}
        public function updatecates(){
                $tips = '正在获取天猫分类.......';
		$this->assign("tips",$tips);
		ob_start();
		ob_end_flush(); 
		ob_implicit_flush(1);
		$this->display("collect");
		echoFlush('<script type="text/javascript"></script>');
		vendor('common');
		if(FS('Goods')->collectTmallCates())
		{
			echoFlush('<script type="text/javascript">setTimeout(function(){location.href="'.U('TmallCollect/setting',array('time'=>TIME_UTC)).'";},1000);</script>');
		}
        }

        public function shop()
	{
		if(!isset($_SESSION['taobao_collect_shop']))
			exit;
			
		if($_SESSION['taobao_collect_shop'] == 0)
		{
			@set_time_limit(3600);
			if(function_exists('ini_set'))
			{
				ini_set('max_execution_time',3600);
				ini_set("memory_limit","256M");
			}
			M()->query('INSERT INTO '.C("DB_PREFIX").'taobao_shop_temp SELECT NULL,nick FROM '.C("DB_PREFIX").'taobao_collect GROUP BY nick');
			file_put_contents(FANWE_ROOT."./public/taobao/collect.lock","1");
		}
		
		$_SESSION['taobao_collect_shop']++;
		$begin = ($_SESSION['taobao_collect_shop'] - 1) * 20;
		$end = $begin + 20;
		
		$tips = '正在采集店铺 '.$cate_name.' 第 '.$begin.' 到 '.$end.' 行';
		$count = D('TaobaoShopTemp')->count();
		$tips .= '<br/>还有 '.$count.' 个店铺未采集';
		$this->assign("tips",$tips);
		
		ob_start();
		ob_end_flush(); 
		ob_implicit_flush(1);
		$this->display("collect");
		echoFlush('<script type="text/javascript"></script>');
		
		vendor('common');
		if(FS("Goods")->collectShop() == 0)
		{
			echoFlush('<script type="text/javascript">setTimeout(function(){location.href="'.U('TmallCollect/shop',array('time'=>TIME_UTC)).'";},1000);</script>');
		}
		else
		{
			$_SESSION['taobao_collect_goods'] = 0;
			$this->redirect('TmallCollect/goods');
		}
	}
	
	public function goods()
	{
		if(!isset($_SESSION['taobao_collect_goods']))
			exit;
		
		$_SESSION['taobao_collect_goods']++;
		$begin = ($_SESSION['taobao_collect_goods'] - 1) * 20;
		$end = $begin + 20;
		
		$tips = '正在获取商品详细 '.$cate_name.' 第 '.$begin.' 到 '.$end.' 行';
		$count = D('TaobaoCollect')->count();
		$tips .= '<br/>还有 '.$count.' 个商品详细未获取';
		
		$this->assign("tips",$tips);
		
		ob_start();
		ob_end_flush(); 
		ob_implicit_flush(1);
		$this->display("collect");
		echoFlush('<script type="text/javascript"></script>');
		
		vendor('common');
		if(FS("Goods")->collectGoods() == 0)
		{
			echoFlush('<script type="text/javascript">setTimeout(function(){location.href="'.U('TmallCollect/goods',array('time'=>TIME_UTC)).'";},1000);</script>');
		}
		else
		{
			$_SESSION['taobao_collect_share'] = 0;
			$this->redirect('TmallCollect/share');
		}
	}
	
	public function share()
	{
		if(!isset($_SESSION['taobao_collect_share']))
			exit;
		
		$_SESSION['taobao_collect_share']++;
		$begin = ($_SESSION['taobao_collect_share'] - 1) * 20;
		$end = $begin + 20;
		
		$tips = '正在发布 '.$cate_name.' 第 '.$_SESSION['taobao_collect_share'].' 个商品分享';
		$count = D('TaobaoShare')->count();
		$tips .= '<br/>还有 '.$count.' 个商品未分享';
		
		$this->assign("tips",$tips);
		
		ob_start();
		ob_end_flush(); 
		ob_implicit_flush(1);
		$this->display("collect");
		echoFlush('<script type="text/javascript"></script>');
		
		vendor('common');
		if(FS("Goods")->share('tmall') == 0)
		{
			echoFlush('<script type="text/javascript">setTimeout(function(){location.href="'.U('TmallCollect/share',array('time'=>TIME_UTC)).'";},1000);</script>');
		}
		else
		{
			$this->assign("jumpUrl",u("TmallCollect/index"));
			@unlink(FANWE_ROOT."./public/taobao/collect.lock");
			$this->success ("采集成功");
		}
	}
	
    public function setting()
	{
            //s: 人气排序 p: 价格从低到高; pd: 价格从高到低; d: 月销量从高到低; td: 总销量从高到低; pt: 按发布时间排序.
		
		$is_collect_lock = file_exists(FANWE_ROOT."./public/taobao/tmallcollect.lock");
		$this->assign("is_collect_lock",$is_collect_lock);
		$cate_keywords = array();
		$config = @include FANWE_ROOT."./public/taobao/tmallcollect.config.php";
		if(!$config)
		{
			$config['sort_order'] =  '';
			$config['page_num'] =  1;
			$config['user_ids'] =  '';
			$config['user_gid'] =  0;
			$config['cate_ids'] =  '';
			$config['keywords'] = '';
		}
		else
		{
			if(!empty($config['user_ids']))
			{
				$user_list = D('User')->where("uid IN (".$config['user_ids'].")")->field('uid,user_name')->select();
				$this->assign("user_list",$user_list);
			}
			
			if(!empty($config['cate_ids']))
			{
				$where['type'] = 'tmall';
				$where['id'] = array('in',$config['cate_ids']);
				$cate_slist = D('TmallCates')->where($where)->select();
				$this->assign("cate_slist",$cate_slist);
			}
                        foreach($cate_slist as $cate)
			{
				$keywords = '';
				if(isset($config['keywords'][$cate['id']]))
					$keywords = $config['keywords'][$cate['id']];
				
				$cate_keywords[] = array(
					'id'=>$cate['id'],
					'name'=>$cate['name'],
					'keywords'=>$keywords,
				);
			}
		}
		$this->assign("vo",$config);
		$this->assign('cate_keywords',$cate_keywords);
                
		$group_list = D("UserGroup")->where('gid <> 6')->getField('gid,name');
		$this->assign("group_list",$group_list);
                
                $is_up = true;
                //天猫分类数据
		if(file_exists(FANWE_ROOT."./public/taobao/tmall_cates_tree.php"))
		{
                        $is_up = false;
                        $cache_data = @include FANWE_ROOT."./public/taobao/tmall_cates_tree.php";
			$cate_list = $cache_data['cate_list'] ;
                        $cate_list_tree = $cache_data['cate_list_tree'] ;
                        if(empty($cate_list)||empty($cate_list_tree))
                            $is_up = true;
                }
                if($is_up){
                        $cate_list_data = D('TmallCates')->where("type='tmall'")->field('id,pid,name')->select();
                        foreach ($cate_list_data as $key=>$value){
                            if(empty($value['pid'])){
                                $cate_list[]=array('id'=>$value['id'],'name'=>$value['name']);
                            }else{
                                $cate_list_tree[$value['pid']][]=array('id'=>$value['id'],'pid'=>$value['pid'],'name'=>$value['name']);
                            }
                        }

                        $cache_data['cate_list'] = $cate_list;
                        $cache_data['cate_list_tree'] = $cate_list_tree;
                        file_put_contents(FANWE_ROOT."./public/taobao/tmall_cates_tree.php", '<?php return '.var_export($cache_data,true).'; ?>');  
                }
                foreach ($cate_list_tree as $key => $value) {
                    $cate_tree_html[$key] = $this->formatcatehtml($value);
                }
               
                $this->assign('cate_tree_html',$cate_tree_html);
                $this->assign('cate_list',$cate_list);
                $this->display();
    }
	

	
	public function clearlock()
	{
		@unlink(FANWE_ROOT."./public/taobao/collect.lock");
		if(file_exists(FANWE_ROOT."./public/taobao/collect.lock"))
		{
			$this->assign("jumpUrl",u("TaobaoCollect/setting"));
			$this->error('取消采集锁定失败，您可以手动删除文件：'.FANWE_ROOT."./public/taobao/collect.lock");
		}
		else
		{
			$this->assign("jumpUrl",u("TaobaoCollect/setting"));
			$this->success ('取消采集锁定成功');
		}
	}
	
	public function update()
	{
		if(empty($_REQUEST['cate_ids']))
		{
			$this->assign("jumpUrl",u("TmallCollect/setting"));
			$this->error ("请设置采集分类");
		}
		
		if(empty($_REQUEST['user_ids']) && (int)$_REQUEST['user_gid'] == 0)
		{
			$this->assign("jumpUrl",u("TmallCollect/setting"));
			$this->error ("请设置会员或者会员组");
		}
		
		if($this->save())
		{
			if((int)$_REQUEST['is_collect'] == 1)
			{
				M()->query('TRUNCATE TABLE '.C("DB_PREFIX").'taobao_collect');
				M()->query('TRUNCATE TABLE '.C("DB_PREFIX").'taobao_shop_temp');
				M()->query('TRUNCATE TABLE '.C("DB_PREFIX").'taobao_share');

				$_SESSION['taobao_collect_cindex'] = 0;
				$_SESSION['taobao_collect_page'] = 1;
				$_SESSION['taobao_collect_errnum'] = 0;
				file_put_contents(FANWE_ROOT."./public/taobao/tmallCollect.lock","1");
				$this->assign("jumpUrl",u("TmallCollect/collect"));
				$this->success (L('EDIT_SUCCESS'));
			}
			else
			{
				$this->assign("jumpUrl",u("TmallCollect/setting"));
				$this->success (L('EDIT_SUCCESS'));
			}
		}
		else
		{
			$this->error (L('EDIT_ERROR'));
		}
    }
	
	public function collect()
	{
		if(!isset($_SESSION['taobao_collect_cindex']) || !isset($_SESSION['taobao_collect_page']))
			exit;

		$config = @include FANWE_ROOT."./public/taobao/tmallcollect.config.php";
		
		if($_SESSION['taobao_collect_page'] > $config['page_num'])
		{
			$_SESSION['taobao_collect_page'] = 1;
			$_SESSION['taobao_collect_cindex']++;
		}

		$cids = explode(',',$config['cate_ids']);
                
                //采集完成
		if($_SESSION['taobao_collect_cindex'] >= count($cids))
		{
			$this->assign("jumpUrl",u("TmallCollect/index"));
			@unlink(FANWE_ROOT."./public/taobao/tmallcollect.lock");
			$this->success ("采集成功");
			exit;
		}
                
		$cate_name = D('TmallCates')->where("type='tmall' and id = '".$cids[$_SESSION['taobao_collect_cindex']]."'")->getField('name');

		$tips = '正在采集分类 '.$cate_name.' 第 '.$_SESSION['taobao_collect_page'].' 页';
		
		if($_SESSION['taobao_collect_errnum'] > 0)
			$tips .= '<br/>已经失败 '.$_SESSION['taobao_collect_errnum'].' 次，失败重采剩余次数 '.(10 - $_SESSION['taobao_collect_errnum']);
			
		$tips .= '<br/>该分类还有 '.($config['page_num'] - $_SESSION['taobao_collect_page']).' 页未采集';
		$tips .= '<br/>还有 '.(count($cids) - 1 - $_SESSION['taobao_collect_cindex']).' 个其他分类未采集';
		
		$this->assign("tips",$tips);
		
		ob_start();
		ob_end_flush(); 
		ob_implicit_flush(1);
		$this->display();
		echoFlush('<script type="text/javascript"></script>');
		
		@set_time_limit(3600);
		sleep(1);
		
		vendor('common');
		if(function_exists('ini_set'))
		{
			ini_set('max_execution_time',3600);
			ini_set("memory_limit","256M");
		}
		$cate_id = $cids[$_SESSION['taobao_collect_cindex']];
		$keywords = trim($config['keywords'][$cate_id]);
		
		$result = FS('Goods')->tmallCollect($cate_id,$keywords,$config['sort_order'],$_SESSION['taobao_collect_page']);
		if($result['status'] == 1)
		{
			$_SESSION['taobao_collect_errnum'] = 0;
			if($_SESSION['taobao_collect_page'] >= $result['max_page'])
			{
				$_SESSION['taobao_collect_page'] = 0;
				$_SESSION['taobao_collect_cindex']++;
			}
		}
		else
		{
			$_SESSION['taobao_collect_errnum']++;
			if($_SESSION['taobao_collect_errnum'] < 10)
			{
				echoFlush('<script type="text/javascript">setTimeout(function(){location.href="'.U('TmallCollect/collect',array('time'=>TIME_UTC)).'";},500);</script>');
				exit;
			}
			else
				$_SESSION['taobao_collect_errnum'] = 0;
		}
		
		$_SESSION['taobao_collect_page']++;
		echoFlush('<script type="text/javascript">setTimeout(function(){location.href="'.U('TmallCollect/collect',array('time'=>TIME_UTC)).'";},1000);</script>');
    }
	
	private function save()
	{
		$config = array();
		
		$config['sort_order'] =  trim($_REQUEST['sort_order']);
		$config['page_num'] =  (int)$_REQUEST['page_num'];
		if($config['page_num'] < 1)
			$config['page_num'] = 1;
			
		if($config['page_num'] > 99)
			$config['page_num'] = 99;
		
		$config['keywords'] = $_REQUEST['keywords'];
		
		$config['user_ids'] =  trim($_REQUEST['user_ids']);
		$config['user_gid'] =  (int)$_REQUEST['user_gid'];
		$config['cate_ids'] =  trim($_REQUEST['cate_ids']);
                
		file_put_contents(FANWE_ROOT."./public/taobao/tmallcollect_setting.lock","1");
		if(@file_put_contents(FANWE_ROOT."./public/taobao/tmallcollect.config.php","<?php\n".'return '.var_export($config, true).";\n\n?>"))
		{
			return true;
		}
		return false;
	}
        
        private function formatcatehtml($data){
               $data_html ='';
                if($data)
                {
                     $data_html ='<select multiple="multiple" class="cateSelect" style="height:400px;">';
                    foreach($data as $k=>$v){
                        $temp_html = '<option parentID="'.$v['pid'].'" value="'.$v['id'].'"> '.$v['name'].'</option>';
                        $data_html.=$temp_html;
                    }
                    $data_html.='</select>';
               }
               return $data_html;
        }
        
        public function remove() {
		//删除指定记录
		$result = array('isErr'=>0,'content'=>'');
		$id = $_REQUEST['id'];
		if(!empty($id))
		{
			$model = D('TaobaoCollect');
			$pk = $model->getPk ();
			$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
			if(false !== $model->where ( $condition )->delete ())
			{
				$this->saveLog(1,$id);
			}
			else
			{
				$this->saveLog(0,$id);
				$result['isErr'] = 1;
				$result['content'] = L('REMOVE_ERROR');
			}
		}
		else
		{
			$result['isErr'] = 1;
			$result['content'] = L('ACCESS_DENIED');
		}
		
		die(json_encode($result));
	}
}

function showGoods($title,$goods)
{
	return '<a href="'.$goods['click_url'].'" target="_blank">'.$title.'</a>';
}

function showShop($nick,$goods)
{
	return '<a href="'.$goods['shop_click_url'].'" target="_blank">'.$nick.'</a>';
}
?>
